﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using ObservadorPeplau.API.Business;

namespace ObservadorPeplau.API.DAL
{
    internal class DiscussionWebDAO
    {
        private readonly HtmlWeb _htmlWeb;

        public DiscussionWebDAO()
        {
            _htmlWeb = new HtmlWeb();
        }

        internal List<Comment> GetCommentsFromWeb(string url)
        {
            var htmlDocument = _htmlWeb.Load(url);
            if (htmlDocument == null)
                return new List<Comment>();

            var articleNodes = htmlDocument.DocumentNode.SelectNodes("//section[@id='comments']/article");
            if (articleNodes == null)
                return new List<Comment>();

            return articleNodes.Select(GetCommentFromHtmlContainer).ToList();
        }

        private Comment GetCommentFromHtmlContainer(HtmlNode container)
        {
            var comment = new Comment();

            // ID
            comment.Id = (container.SelectSingleNode("a[@name]") != null)
                             ? container.SelectSingleNode("a[@name]").GetAttributeValue("name", -1)
                             : -1;

            if (container.SelectSingleNode("div[@class='post-header left-img-45']") != null)
            {
                // Author
                comment.Author = new Author()
                                     {
                                         Name = container.SelectSingleNode("div[@class='post-header left-img-45']/span[@class='metas']/a").InnerText,
                                         Login = container.SelectSingleNode("div[@class='post-header left-img-45']/span[@class='metas']/a").GetAttributeValue("href","").Replace(Constants.AuthorUrl,"").Replace("/",""),
                                         ImageUrl = container.SelectSingleNode("div[@class='post-header left-img-45']/img").GetAttributeValue("src","")
                                     };

                // Datetime
                var rawText = container.SelectSingleNode("div[@class='post-header left-img-45']/span[@class='metas']").InnerText;

                var startIndex = rawText.IndexOf(", em") + 5;
                var stringLength = rawText.LastIndexOf(".") - startIndex;
                var dateTimePart = rawText.Substring(startIndex, stringLength).Replace("às ", "");
                var datePart = dateTimePart.Split(' ')[0];
                var hourPart = dateTimePart.Split(' ')[1];
                var day = int.Parse(datePart.Split('/')[0]);
                var mon = int.Parse(datePart.Split('/')[1]);
                var yea = int.Parse(datePart.Split('/')[2]);
                var hou = int.Parse(hourPart.Split(':')[0]);
                var min = int.Parse(hourPart.Split(':')[1]);

                comment.DateTime = new DateTime(yea, mon, day, hou, min, 0);
            }

            // Text
            comment.Text = String.Join("", container.SelectNodes("p").Select(p => p.OuterHtml).ToArray());

            // Get Children Comments (if any)
            comment.Children = new List<Comment>();
            var childrenNodes = container.SelectNodes("div[@class='child'] | div[@class='child2']");
            if (childrenNodes != null)
            {
                Comment commentLevel1 = null;
                Comment commentLevel2 = null;
                foreach (var childrenNode in childrenNodes)
                {
                    if (childrenNode.GetAttributeValue("class", "") == "child")
                    {
                        commentLevel1 = GetCommentFromHtmlContainer(childrenNode);
                        commentLevel1.Parent = comment;
                        comment.Children.Add(commentLevel1);
                    }
                    else if (childrenNode.GetAttributeValue("class", "") == "child2")
                    {
                        commentLevel2 = GetCommentFromHtmlContainer(childrenNode);
                        commentLevel2.Parent = commentLevel1;
                        if (commentLevel1 != null)
                            commentLevel1.Children.Add(commentLevel2);
                    }
                }
            }

            return comment;
        }
    }
}
